﻿/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Reflection;
using System.Diagnostics;

namespace IvyOrm
{
    /// <summary>
    /// Provides a GetFactory() extensions to the DbConnection object
    /// </summary>
    public static class GetFactoryExtension
    {
        static Dictionary<Type, DbProviderFactory> getFactoryCache = new Dictionary<Type, DbProviderFactory>();

        /// <summary>
        /// Returns an  factory instance associated with the specified connection type by looking in the assembly for class that derives from DbProviderFactory.
        /// </summary>
        /// <param name="connection"></param>
        /// <returns>Associated factory instance</returns>
        /// <exception cref="System.NotSupportedException" />
        /// <exception cref="System.ArgumentNullException" />
        public static DbProviderFactory GetFactory(this DbConnection connection)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");

            var connectionType = connection.GetType();

            DbProviderFactory factory;
            if (getFactoryCache.TryGetValue(connectionType, out factory))
                return factory;

            factory = GetFactory(connectionType);

            lock (getFactoryCache)
            {
                if (getFactoryCache.ContainsKey(connectionType))
                    return getFactoryCache[connectionType];

                getFactoryCache.Add(connectionType, factory);
                return factory;
            }
        }

        private static DbProviderFactory GetFactory(Type connectionType)
        {
            Debug.Assert(connectionType != null);

            var assembly = connectionType.Assembly;

            var factories = assembly.GetTypes().Where((t) => t.Namespace == connectionType.Namespace &&
                                                             typeof(DbProviderFactory).IsAssignableFrom(t) &&
                                                             t.GetField("Instance", BindingFlags.Public | BindingFlags.Static) != null &&
                                                             !t.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any()
                                                      ).ToList();
            if (factories.Count == 0)
                throw new NotSupportedException("Unable to identify " + typeof(DbProviderFactory).Name + " for " + connectionType.FullName + ", no factories found");
            else if (factories.Count > 1)
                throw new NotSupportedException("Unable to identify " + typeof(DbProviderFactory).Name + " for " + connectionType.FullName + ", multiple factories found");

            var factoryType = factories[0];
            var instanceField = factoryType.GetField("Instance", BindingFlags.Public | BindingFlags.Static);
            var instance = instanceField.GetValue(null) as DbProviderFactory;

            if (instance == null)
                throw new NotSupportedException("Invalid factory for " + connectionType.FullName + ", " + factoryType.FullName + ".Instance returned null");

            return instance;
        }
    }
}
